<template>
  <div>
    <jm-head></jm-head>



    <input type="file" id="fileInput" accept="image/png,image/gif,image/jpeg" ref="fileInput" v-on:change="addImg"/>

    <section class="form">

        <section class="room_name">
          <input type="text" placeholder="空间名" v-model="roomName" @blur="roomNameRight">
        </section>

        <section class="room_cover">

          <section class="img_box" @click="uploadClick" :class="{'img_box_active': show }">
            <i class="icon_style iconfont icon-tupian1" slot="item_btn" v-show="!show && !showLoad"></i>
            <span v-show="!show && !showLoad">空间封面</span>
            <img src="" alt="" id="img_show" v-show="show" class="cover">
            <spinner type="snake" v-show="showLoad" class="load_icon"></spinner>
          </section>
        </section>

        <section class="room_signature">
          <textarea class="input_item" placeholder="请输入空间简介" v-model="signature" @blur="signatureRight"></textarea>
        </section>

        <section class="room_type">
          <p class="type_header">空间类型：</p>
          <p class="type_container">
            <section class="type_item">
              <input type="radio" name="type" value="-1" v-model="roomType"/>
              个人空间
            </section>

            <section class="type_item">
              <input type="radio" checked="checked" name="type" value="1" v-model="roomType"/>
              私人空间
            </section>

            <section class="type_item">
              <input type="radio" name="type" value="0" v-model="roomType"/>
              公共空间
            </section>
          </p>
        </section>
    </section>
    <button class="btn" @click="create">创建空间</button>
    <jm-footer></jm-footer>
  </div>

</template>

<script>
  import JmHead from '../../components/header/Head';
  import JmFooter from '../../components/footer/Footer';
  import CryptoJS from 'crypto-js'
  import Uploader from '../../service/nos-js-sdk';
  import {mapState, mapMutations} from 'vuex'
  import { Toast,Spinner } from 'mint-ui';

    export default {
      data () {
        return {
          cover: null,  //空间封面
          roomName: null,  //封面名称
          coverUrl:null,  //封面的url
          signature: null,  //空间的介绍
          roomType: 1,  //空间类型，1为私有类型，0为公共类型，-1为个人类型
          result: null,  //创建空间的结果
          show: false,  //展示图片
          showLoad: false, //展示加载
        }
      },

      methods: {
        roomNameRight(){
          if (this.roomName === null){
            let instance = Toast({message: '空间名不能为空', className: 'toast'});
            setTimeout(() => {
              instance.close();
            }, 2000);
            return
          }

          if (this.roomName.length > 10){
            let instance = Toast({message: '空间名长度不能超过10位', className: 'toast'});
            setTimeout(() => {
              instance.close();
            }, 2000);
            return
          }
        },
        signatureRight(){
          if (this.signature === null){
            let instance = Toast({message: '空间简介不能为空', className: 'toast'});
            setTimeout(() => {
              instance.close();
            }, 2000);
            return
          }
        },
        uploadClick(){
          document.getElementById("fileInput").click();
        },


        addImg(){
          let fileinput = document.getElementById('fileInput');
          let image = fileinput.files[0];

          let reader = new FileReader();
          reader.readAsBinaryString(image);

          reader.onload = function (e) {
            let name = CryptoJS.MD5(e.target.result).toString()+'.jpg';
            this.uploadImg(image, name);
          }.bind(this)

        },

        showImg(fileName){
          this.show = true;
          this.showLoad = false;
          this.coverUrl = fileName;
          document.getElementById("img_show").src =this.$store.state.baseImgUrl +  this.coverUrl;
        },


        uploadImg(image, fileName){
          this.showLoad = true;
          let that = new Uploader();

          let param = {
            bucketName: 'jimikongjian',
            objectName: fileName,
            token: this.getToken(fileName),
            trunkSize: 4 * 1024 * 1024,
          }

          if (image) {
            that.addFile(image, function(curFile){
              console.log(curFile.fileName + ' is added.');
            });
            that.upload(param, function(curFile){
              console.log('File: ' + curFile.fileName + ' is uploaded.');
              this.showImg(fileName);
            }.bind(this));

          }

        },


        //获取上传凭证
        getToken(Object){
          let p = {
            "Bucket" : "jimikongjian",
            "Object" : Object,
            "Expires" : this.$store.state.expiresTime
          }
          let putPolicy = JSON.stringify(p);
          let wordArray = CryptoJS.enc.Utf8.parse(putPolicy);
          let encodedPutPolicy = CryptoJS.enc.Base64.stringify(wordArray);
          let sign = CryptoJS.HmacSHA256(encodedPutPolicy, this.$store.state.accessSecret);
          let encodedSign = CryptoJS.enc.Base64.stringify(sign);
          return "UPLOAD " + this.$store.state.accessKey + ":" + encodedSign + ":" + encodedPutPolicy;
        },



        async create(){
          if (this.roomName === null){
            let instance = Toast({message: '空间名不能为空', className: 'toast'});
            setTimeout(() => {
              instance.close();
            }, 2000);
            return
          }
          if (this.coverUrl === null){
            let instance = Toast({message: '空间封面不能为空', className: 'toast'});
            setTimeout(() => {
              instance.close();
            }, 2000);
            return
          }
          if (this.signature === null){
            let instance = Toast({message: '空间简介不能为空', className: 'toast'});
            setTimeout(() => {
              instance.close();
            }, 2000);
            return
          }

          if (this.roomName.length > 10){
            let instance = Toast({message: '空间名长度不能超过10位', className: 'toast'});
            setTimeout(() => {
              instance.close();
            }, 2000);
            return
          }

          let room = {
            name: this.roomName, //空间的名称
            cover: this.coverUrl,  //空间的封面
            creatorId: this.$store.state.userInfo.userId,  //空间创建者的用户id
            creatorEmail: this.$store.state.userInfo.email,  //空间创建者的邮箱
            creatorNick: this.$store.state.userInfo.nick,  //空间创建者的昵称
            signature: this.signature,  //空间的简介
            type: this.roomType,  //空间的类型
            peoples: 1,  //空间的人数
          }

          await this.axios.post('/v1/room', room)
            .then(response => {
            this.result = response.data;
          });
          console.log(this.result);
          if (this.result.success){
            let instance = Toast({message: '创建空间成功', className: 'toast'});
            setTimeout(() => {
              instance.close();
              this.$router.push('home');
            }, 2000);

          }else{
            let instance = Toast({message: '网络连接失败', className: 'toast'});
            setTimeout(() => {
              instance.close();
            }, 2000);
          }
        }


      },
      mounted () {

      },
      components:{
        Spinner,
        JmHead,
        JmFooter
      }
    }
</script>

<style lang="scss">
  .mint-toast-text{
    font-size: 0.6rem;
  }
  .toast{
    min-width: 180px;
    width: 180px;
    span{
      color: #FFFFFF;
    }
  }
  .mint-spinner-snake{
    margin: auto auto;
  }
</style>

<style lang="scss" scoped>
  @import '../../style/mixin';
  .load_icon{
    display: inline-block;
    height: 100%;
    width: 100%;
    position: relative;
    margin: 0 auto;
  }

  #fileInput{
    position: absolute;
    top: 0;
    left: 0;
    width: 0;
    height: 0;
  }

  .form{
    overflow: hidden;
    height: 399px;
    width: 80%;
    margin: 0 10%;
    margin-top: 2rem;
    margin-bottom: 0.7rem;
    border: solid 1px #666;
    @include borderRadius(15px);

    .room_name{
      height: 30px;
      width: 100%;
      border-bottom: solid 1px #666;

    }

    .room_cover{
      height: 150px;
      width: 100%;
      border-bottom: solid 1px #666;
      display: flex;

      .img_box{
        border: dashed 1px #666;
        width: 90%;
        height: 130px;
        margin: 10px auto;
        display: flex;
        text-align: center;
        flex-direction: column;
        align-items: center;

        .icon_style{
          color: #666;
          font-size: 69px;
          margin: auto auto;
        }
        span{
          font-size: 15px;
        }


        .cover{
          width: 100%;
          height: 100%;
          margin: 0;
        }


      }

    }

    .room_signature{
      height: 150px;
      width: 100%;
      border-bottom: solid 1px #666;

      .input_item{
        height: 100%;
        width: 100%;
        font-size: 15px;
        text-indent: 13px;
        resize: none;
      }
    }

    .room_type{
      height: 66px;
      width: 100%;

      .type_header{
        font-size: 15px;
        margin: 5px 13px;
      }

      .type_container{
        display: flex;
        width: 100%;
        margin: 2px 13px;

        .type_item{
          flex: 1;
          display: flex;
          /*text-align: center;*/
          /*flex-direction: column;*/
          align-items: center;
          margin: auto auto;
          font-size: 15px;

          input{
            width: 15px;
            height: 15px;
          }
        }
      }

    }

    input{
      background-color: transparent;
      height: 100%;
      width: 100%;
      font-size: 15px;
      text-indent: 13px;
    }


    ::-webkit-input-placeholder{
      color: #666;
      font-size: 15px;
      text-indent: 13px;
    }
    :-moz-placeholder { /* Mozilla Firefox 4 to 18 */
      color: #666;
      font-size: 15px;
      text-indent: 13px;
    }
    ::-moz-placeholder { /* Mozilla Firefox 19+ */
      color: #666;
      font-size: 15px;
      text-indent: 13px;
    }
    :-ms-input-placeholder { /* Internet Explorer 10+ */
      color: #666;
      font-size: 15px;
      text-indent: 13px;
    }

  }

  .btn{
    height: 30px;
    width: 80%;
    margin: 0 10%;
    background-color: #33CCFF;
    color: #FFFFFF;
    @include borderRadius(15px);
    font-size: 20px;
    font-weight: bold;
  }
</style>
